<?php


/**
 * Patient Handler class 
 *
 * @author [samantha Jayasinghe] [isamantha@gmail.com]
 */
class PatientHandler {
    
    /**
     * Search Patient 
     * @param type $searchParms
     */
    public function searchPatients( $post ){
        $searchParms         = array();
        $searchParms = $this->getSearchParameters( $post );
        
        if( count($searchParms ) == 0)
            throw new Exception(" Please enter search parameters ");
        
        $pdo = DbConnection::getInstance()->conn;
        $params = array();
        $where  = array();
        $sql = "SELECT * FROM pt  " ;
        if(!empty($searchParms['id'])){
            
            $whereHid   = " hid LIKE ?  ";
            array_push($where, $whereHid);
            array_push($params, '%'.$searchParms['id'].'%');
        }
        if(!empty($searchParms['name']) ){
            $whereName = " ( (CONCAT_WS(' ',fname,mname,sname) LIKE ? ) OR (fname LIKE ? OR mname LIKE ? OR sname LIKE ?) )";
            array_push($where, $whereName);
            array_push($params, '%'.$searchParms['name'].'%');
            array_push($params, '%'.$searchParms['name'].'%');
            array_push($params, '%'.$searchParms['name'].'%');
            array_push($params, '%'.$searchParms['name'].'%');
        }
        if(!empty($searchParms['sex'])){
            
            $whereSex = " sex = ?";
            array_push($where, $whereSex);
            array_push($params, $searchParms['sex']);
        }
        if( count($where) > 0){
            $sql .= " WHERE ".implode(" AND ", $where);
        }
        
        $query = $pdo->prepare($sql);
        $query->execute($params);
        
        return $query->fetchAll();
    }
    
    /**
     * Search Patient By Name
     * @param type $name
     */
    public function searchPatientByName( $name ,$yy,$mm,$dd){
         $pdo = DbConnection::getInstance()->conn;
         $params = array();
         $where  = array();
         $sql = "SELECT pid,hid,CONCAT_WS(' ',fname,mname,sname) as fullName,dob, sex FROM pt  " ;
         if(!empty($name ) ){
            $whereName = " ( (CONCAT_WS(' ',fname,mname,sname) LIKE ? ) OR (fname LIKE ? OR mname LIKE ? OR sname LIKE ?) )";
            array_push($where, $whereName);
            array_push($params, '%'.$name.'%');
            array_push($params, '%'.$name.'%');
            array_push($params, '%'.$name.'%');
            array_push($params, '%'.$name.'%');  
         }
         if( is_numeric($yy) ){
            
            $whereDob = " DATE_FORMAT(dob,'%Y')  = ? ";
            array_push($where, $whereDob);
            array_push($params, $yy);
         }
         /*if(is_numeric($mm) ){
            
            $whereDob = " DATE_FORMAT(dob,'%m')  = ? ";
            array_push($where, $whereDob);
            array_push($params, $mm);
         }
         if(is_numeric($dd) ){
            
            $whereDob = " DATE_FORMAT(dob,'%d')  = ? ";
            array_push($where, $whereDob);
            array_push($params, $dd);
         } 
         if(is_numeric($yy) && is_numeric($mm) && is_numeric($dd) ){
            
            $whereDob = " dob  = ? ";
            array_push($where, date('Y-m-d',  strtotime($yy.'-'.$mm.'-'.$dd)));
            array_push($params, $dd);
         }
         */
         
         if( count($where) > 0){
            $sql .= " WHERE ".implode(" AND ", $where)." LIMIT 10";
        }
        
        $query = $pdo->prepare($sql);
        $query->execute($params);
        
        return $query->fetchAll();
    }
    
    /**
     * Save Patient 
     * 
     * @param type $patientInfo
     */
    public function savePatient( $patientInfo ){
       $pdo     = DbConnection::getInstance()->conn;
       $user    = Authentication::getLogedinUser();
       $hid     =   $this->getHelthId($patientInfo['yy'], $patientInfo['mm'], $patientInfo['dd'], $patientInfo['sex']);
       
       $ct = time();
       $sql     =   "INSERT INTO pt ( hid, fname, mname, sname, yy, mm, dd, dob, sex, ct, cid, eid, lid)";
       $sql     .=  " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)"; 
       $query  = $pdo->prepare($sql);
       $query->execute(array($hid , $patientInfo['fname'],$patientInfo['mname'],$patientInfo['sname'], $patientInfo['yy'], $patientInfo['mm'], $patientInfo['dd'],$patientInfo['dob'], $patientInfo['sex'],$ct,$user->getUserId(),$user->getUserId(),$user->getUserId()));
       
       $_SESSION['pid'] = $pdo->lastInsertId();
    }
    
    public function updatePatient( $patientInfo ){
       $pdo     = DbConnection::getInstance()->conn;
       $user    = Authentication::getLogedinUser();
       $hid     =   $this->getHelthId($patientInfo['yy'], $patientInfo['mm'], $patientInfo['dd'], $patientInfo['sex']);
       
        $sql     =   "UPDATE pt SET hid=?, fname=?, mname=?, sname=?, yy=?, mm=?, dd=?, dob=?, sex=? WHERE pid=?";
        $query  = $pdo->prepare($sql);
        $query->execute(array($hid , $patientInfo['fname'],$patientInfo['mname'],$patientInfo['sname'], $patientInfo['yy'], $patientInfo['mm'], $patientInfo['dd'],$patientInfo['dob'], $patientInfo['sex'],$patientInfo['pid']));
        
        $_SESSION['pid'] = $patientInfo['pid'];
    }
    
    /**
     * Get helth Id
     * 
     * @param type $yy
     * @param type $mm
     * @param type $dd
     * @param type $sex
     * @return string
     */
    private function getHelthId( $yy ,$mm , $dd ,$sex ){
        
        $pdo    = DbConnection::getInstance()->conn;
        $params = array();
        $query  = $pdo->prepare("SELECT hid FROM pt WHERE yy = ? AND mm = ? AND dd = ? AND sex = ? ORDER BY pid DESC LIMIT 1 ");
        $affectedRows = $query->execute(array($yy ,$mm , $dd ,$sex));
        $result = $query->fetch();
        
        $yd = date("z",strtotime($yy.'-'.$mm.'-'.$dd)) + 1 ;
        if ($sex == 'F') { 
            $yd = $yd + 500; 
        }
        $yd = sprintf("%03d",$yd);
        
        if( $affectedRows == 0){
            $hid = $yy.$yd.'001';
        }else{
            $hid = $result['hid'] ;
            $sn = ($hid % 1000) + 1 ;
            $sn = sprintf("%03d",$sn) ;
            $hid = $yy.$yd.$sn ;
        }
        return $hid;
         
    }
    
    /**
     * Get Search Parameters 
     * 
     * @param type $post
     * @return type
     */
    public function getSearchParameters( $post){
        
        $searchParms         = array();
        if(!empty($post['hid'])){
            $searchParms['id']   = trim($post['hid']);
        }
        if(!empty($post['name'])){
            $searchParms['name'] = trim($post['name']);
        }
        if(!empty($post['sex'])){
            $searchParms['sex']  = trim($post['sex']);
        }
        if(!empty($post['yy'])){
             $searchParms['yy']   = trim($post['yy']);
        }
        if(!empty($post['mm'])){
            $searchParms['mm']   = trim($post['mm']);
        }
        if(!empty($post['dd'])){
            $searchParms['dd']   = trim($post['dd']);
        }
        
        return $searchParms;
    }
    
    /**
     * Get Patient Info 
     * 
     * @param type $pid
     */
    public function getPatient( $pid ){
        $pdo    = DbConnection::getInstance()->conn;
        $params = array();
        $query  = $pdo->prepare("SELECT * FROM pt WHERE pid=? LIMIT 1 ");
        $affectedRows = $query->execute(array($pid));
        $result = $query->fetch();
        
        $patient = new Patient();
        
        $patient->id = $result['pid'];
        $patient->code = $result['hid'];
        $patient->firstName = $result['fname'];
        $patient->middleName = $result['mname'];
        $patient->lastName = $result['sname'];
        $patient->dob = $result['dob'];
        $patient->sex = $result['sex'];
        $patient->gardinTitle = $result['ptit'];
        $patient->gardinName = $result['pname'];
        $patient->homeAddress = $result['addr']; 
        
        return $patient ;
    }
    
    private function isValidDate( $date ){
        try {
            $dt = new DateTime( trim($date) );
        }
        catch( Exception $e ) {
            return false;
        }
        $month = $dt->format('m');
        $day = $dt->format('d');
        $year = $dt->format('Y');
        if( checkdate($month, $day, $year) ) {
            return true;
        }
        else {
            return false;
        }
    }
}


